import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_elf/utils/permission_utils.dart';
import 'package:flutter_elf/utils/common_utils.dart';
import 'package:flutter_elf/utils/print_utils.dart';
import 'package:flutter_elf/utils/to_store.dart';
//import 'package:install_apk_plugin/install_apk_plugin.dart';
import 'package:permission_handler/permission_handler.dart';

import '../r.dart';
class UpdateWidget extends StatefulWidget{
  final String sDescription;
  final String url;
  final String versionCode;
  final String versionName;
  final bool isMandatory;//是否强制更新
  UpdateWidget(this.sDescription, this.url, this.versionCode, this.versionName,{this.isMandatory = false});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return UpdateWidgetState();
  }
}

class UpdateWidgetState extends State<UpdateWidget>{
  static StreamController<double> progressStreamer ;
  static int currentTime;
  static String fileName;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  init()async{
    progressStreamer = new StreamController();
    currentTime = DateTime.now().millisecondsSinceEpoch;
    Directory p = await CommonUtils.getLocalPath();
    globalPrint('安装包路径 ====>' + p.path);
    fileName = p.path + '/$currentTime.apk';
  }

  @override
  Widget build(BuildContext context) {
    Widget result = StreamBuilder<double>(
      stream: progressStreamer.stream,
      initialData: 0,
      builder: (context,s){
        return AlertDialog(
          contentPadding: EdgeInsets.only(top: 12,left: 12,right: 12,bottom: 12),
          backgroundColor: Colors.white,
//          title: new Text('版本更新'),
          content: Container(
            color: Colors.white,
            child: ListView(
              shrinkWrap: true,
              children: <Widget>[
                Stack(
                  alignment: Alignment.topCenter,
                  children: <Widget>[
                    Image.asset(R.staticIconsAircorpY8Png,height: 150,width: 175,),
                    Positioned(
                        bottom: 0,
                        right: 0,
                        child: Text(widget.versionName,style: TextStyle(color: Colors.lightBlue),))
                  ],
                ),
                SizedBox(height: 5),
                Align(
                    alignment: Alignment.centerLeft,
                    child: Text(widget.sDescription,softWrap: true,)),
                SizedBox(height: 5),
                Container(
                    child: Row(
                      children: <Widget>[
                        Expanded(child: LinearProgressIndicator(value: (s.data),valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),)),
                        SizedBox(width: 10,),
                        Text('${(s.data*100).toStringAsFixed(2)}%',style: TextStyle(fontSize: 10,color: Colors.lightBlue),)
                      ],
                    )),
              ],
            ),
          ),
          actions: <Widget>[
            new FlatButton(
                onPressed: () {
                  if(!widget.isMandatory){
                    Navigator.pop(context);
                  }
                },
                child: new Text(widget.isMandatory ? '' :'取消',style: TextStyle(color: widget.isMandatory ? Colors.grey : Colors.lightBlue),)),
            new FlatButton(
              onPressed: () {
                if(Platform.isAndroid){
                  if(s.data == 0){//进度为 0
                    update(widget.url,context);
                  }else if(s.data == 1){
                    installApk(fileName);
                  }else{//正在下载中
                    CommonUtils.showToast('正在下载中...');
                  }
                }else{//iOS不做处理

                }
              },
              child: new Text(s.data == 1 ? '安装' : '确定',style: TextStyle(color: s.data != 0 ? Colors.grey  :  Colors.lightBlue),),),
            new FlatButton(onPressed: (){
              GoToStoreUtils.goToMarket();
            }, child: Text('去商店'))
          ],
        );
      },
    );
    if(widget.isMandatory){
      return WillPopScope(
        onWillPop: (){
        },
        child: result,
      );
    }else{
      return result;
    }
  }

  @override
  void dispose() {
    super.dispose(); //删除监听器
    progressStreamer?.close();
  }

  ///提示版本更新
  static bool isDownloading = false;
  static int failedTimes = 0;

  static void update(url,context) async{
    if(isDownloading){
      CommonUtils.showToast('后台正在下载中,您可以点击取消关闭此窗口');return;
    }
    isDownloading = true;
    await PermissionUtils.checkPermission();
    Response response;
    try {
      Dio dio = new Dio();
      response = await dio.download( url, fileName,onReceiveProgress: (i,j){
        if(i != 0 && j != 0){
          globalPrint('=========' + i.toString() + '=============' + j.toString() + '进度==' + (i / j).toString());
          progressStreamer.sink.add(i / j);
        }
      });
      globalPrint('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      globalPrint('downloadFile error---------$e');
      CommonUtils.showToast('下载失败');
    }
    if(response.statusCode == 200){
      CommonUtils.showToast('下载成功');
      installApk(fileName);
      progressStreamer.close();
    }else{
      if (failedTimes < 3) {
        CommonUtils.showToast('下载失败,将为您重新下载');
        failedTimes ++;
        update(url,context);
      } else {

      }
    }
  }

  static installApk(String _apkFilePath)async{
    if (_apkFilePath.isEmpty) {
      globalPrint('make sure the apk file is set');
      return;
    }
    await PermissionUtils.checkPermission();

//      InstallApkPlugin.installApk(_apkFilePath)
//          .then((result) {
//        globalPrint('install apk $result');
//      }).catchError((error) {
//        globalPrint('install apk error: $error');
//      });
//    } else {
//      globalPrint('Permission request fail!');
//    }
  }

}